import { ExtensionSettings, MessageType, TabInfo } from '../types';

// 扩展默认设置
const DEFAULT_SETTINGS: ExtensionSettings = {
  theme: 'light',
  language: 'zh-CN',
  autoUpdate: true,
  enableNotifications: true
};

/**
 * Service Worker for Chrome Extension
 * 处理扩展的后台逻辑，包括消息传递、存储管理、权限处理等
 */
class ExtensionBackground {
  private settings: ExtensionSettings = DEFAULT_SETTINGS;

  constructor() {
    this.init();
  }

  private async init() {
    // 初始化设置
    await this.loadSettings();
    
    // 设置事件监听器
    this.setupEventListeners();
    
    // 初始化通知
    this.setupNotifications();
    
    console.log('Extension background script initialized');
  }

  /**
   * 加载用户设置
   */
  private async loadSettings() {
    try {
      const result = await chrome.storage.sync.get(['settings']);
      if (result.settings) {
        this.settings = { ...DEFAULT_SETTINGS, ...result.settings };
      } else {
        // 首次安装，保存默认设置
        await chrome.storage.sync.set({ settings: DEFAULT_SETTINGS });
      }
    } catch (error) {
      console.error('Failed to load settings:', error);
    }
  }

  /**
   * 设置事件监听器
   */
  private setupEventListeners() {
    // 监听来自 popup、content script 等的消息
    chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
      console.log('Background: Message listener triggered');
      this.handleMessage(message, sender, sendResponse);
      return true; // 保持消息通道开放
    });

    // 监听扩展安装/更新事件
    chrome.runtime.onInstalled.addListener((details) => {
      this.handleInstalled(details);
    });

    // 监听标签页更新事件
    chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
      this.handleTabUpdated(tabId, changeInfo, tab);
    });

    // 监听标签页激活事件
    chrome.tabs.onActivated.addListener((activeInfo) => {
      this.handleTabActivated(activeInfo);
    });

    // 监听存储变化事件
    chrome.storage.onChanged.addListener((changes, namespace) => {
      this.handleStorageChanged(changes, namespace);
    });
  }

  /**
   * 处理消息
   */
  private async handleMessage(
    message: any,
    sender: chrome.runtime.MessageSender,
    sendResponse: (response?: any) => void
  ) {
    console.log('Background: Received message:', message, 'from:', sender);
    try {
      switch (message.type) {
        case MessageType.GET_SETTINGS:
          console.log('Background: Handling GET_SETTINGS');
          sendResponse({ success: true, data: this.settings });
          break;

        case MessageType.UPDATE_SETTINGS:
          console.log('Background: Handling UPDATE_SETTINGS with payload:', message.payload);
          await this.updateSettings(message.payload);
          sendResponse({ success: true });
          break;

        case MessageType.TOGGLE_FLOAT_BOX:
          console.log('Background: Handling TOGGLE_FLOAT_BOX for tab:', sender.tab?.id);
          // 如果消息来自 popup，需要获取当前活动标签页
          let targetTabId = sender.tab?.id;
          if (!targetTabId) {
            const [activeTab] = await chrome.tabs.query({ active: true, currentWindow: true });
            targetTabId = activeTab?.id;
            console.log('Background: Using active tab ID:', targetTabId);
          }
          await this.toggleFloatBox(targetTabId);
          sendResponse({ success: true });
          break;

        case MessageType.GET_TAB_INFO:
          console.log('Background: Handling GET_TAB_INFO');
          const tabInfo = await this.getTabInfo(sender.tab?.id);
          sendResponse({ success: true, data: tabInfo });
          break;

        case MessageType.OPEN_SIDE_PANEL:
          console.log('Background: Handling OPEN_SIDE_PANEL');
          // 如果消息来自 popup，需要获取当前活动标签页
          let sideTabId = sender.tab?.id;
          if (!sideTabId) {
            const [activeTab] = await chrome.tabs.query({ active: true, currentWindow: true });
            sideTabId = activeTab?.id;
            console.log('Background: Using active tab ID for sidepanel:', sideTabId);
          }
          await this.openSidePanel(sideTabId);
          sendResponse({ success: true });
          break;

        case 'ERROR_REPORT':
          console.log('Background: Handling ERROR_REPORT');
          await this.handleErrorReport(message.payload);
          sendResponse({ success: true });
          break;

        case 'GLOBAL_ERROR_REPORT':
          console.log('Background: Handling GLOBAL_ERROR_REPORT');
          await this.handleGlobalErrorReport(message.payload);
          sendResponse({ success: true });
          break;

        default:
          console.log('Background: Unknown message type:', message.type);
          sendResponse({ success: false, error: 'Unknown message type' });
      }
    } catch (error) {
      console.error('Error handling message:', error);
      sendResponse({ success: false, error: (error as Error).message });
    }
  }

  /**
   * 处理扩展安装/更新事件
   */
  private async handleInstalled(details: chrome.runtime.InstalledDetails) {
    if (details.reason === 'install') {
      // 首次安装
      console.log('Extension installed');
      
      if (this.settings.enableNotifications && chrome.notifications) {
        chrome.notifications.create({
          type: 'basic',
          iconUrl: 'icons/icon48.png',
          title: '扩展安装成功',
          message: '欢迎使用 Chrome 扩展！点击工具栏图标开始使用。'
        });
      }

      // 打开欢迎页面
      chrome.tabs.create({
        url: chrome.runtime.getURL('settings.html')
      });
    } else if (details.reason === 'update') {
      // 扩展更新
      console.log('Extension updated');
      
      if (this.settings.enableNotifications && chrome.notifications) {
        chrome.notifications.create({
          type: 'basic',
          iconUrl: 'icons/icon48.png',
          title: '扩展已更新',
          message: '扩展已更新到最新版本！'
        });
      }
    }
  }

  /**
   * 处理标签页更新事件
   */
  private handleTabUpdated(
    tabId: number,
    changeInfo: chrome.tabs.TabChangeInfo,
    tab: chrome.tabs.Tab
  ) {
    // 页面加载完成时的处理
    if (changeInfo.status === 'complete' && tab.url) {
      // 可以在这里添加页面分析、内容检测等功能
      console.log(`Tab ${tabId} updated:`, tab.url);
    }
  }

  /**
   * 处理标签页激活事件
   */
  private handleTabActivated(activeInfo: chrome.tabs.TabActiveInfo) {
    // 标签页切换时的处理
    console.log(`Tab ${activeInfo.tabId} activated`);
  }

  /**
   * 处理存储变化事件
   */
  private handleStorageChanged(
    changes: { [key: string]: chrome.storage.StorageChange },
    namespace: string
  ) {
    if (namespace === 'sync' && changes.settings) {
      this.settings = changes.settings.newValue;
      console.log('Settings updated:', this.settings);
    }
  }

  /**
   * 更新设置
   */
  private async updateSettings(newSettings: Partial<ExtensionSettings>) {
    this.settings = { ...this.settings, ...newSettings };
    await chrome.storage.sync.set({ settings: this.settings });
  }

  /**
   * 切换悬浮框显示
   */
  private async toggleFloatBox(tabId?: number) {
    console.log('Background: toggleFloatBox called with tabId:', tabId);
    if (!tabId) {
      console.error('Background: No valid tab ID provided for toggleFloatBox');
      return;
    }

    try {
      console.log('Background: Sending TOGGLE_FLOAT_BOX message to tab:', tabId);
      await chrome.tabs.sendMessage(tabId, {
        type: 'TOGGLE_FLOAT_BOX'
      });
      console.log('Background: Successfully sent message to content script');
    } catch (error) {
      // 如果内容脚本未注入，先注入再发送消息
      console.log('Background: Content script not found, injecting...');
      console.error('Background: Error details:', error);
      
      try {
        await chrome.scripting.executeScript({
          target: { tabId },
          files: ['content-script.js']
        });
        console.log('Background: Content script injected successfully');
        
        // 等待一会再发送消息
        setTimeout(async () => {
          try {
            console.log('Background: Retrying message send after injection');
            await chrome.tabs.sendMessage(tabId, {
              type: 'TOGGLE_FLOAT_BOX'
            });
            console.log('Background: Message sent successfully after injection');
          } catch (e) {
            console.error('Background: Failed to toggle float box after injection:', e);
          }
        }, 100);
      } catch (injectionError) {
        console.error('Background: Failed to inject content script:', injectionError);
      }
    }
  }

  /**
   * 获取标签页信息
   */
  private async getTabInfo(tabId?: number): Promise<TabInfo | null> {
    if (!tabId) return null;

    try {
      const tab = await chrome.tabs.get(tabId);
      return {
        id: tab.id!,
        url: tab.url!,
        title: tab.title!,
        active: tab.active
      };
    } catch (error) {
      console.error('Failed to get tab info:', error);
      return null;
    }
  }

  /**
   * 打开侧边栏
   */
  private async openSidePanel(tabId?: number) {
    if (!tabId) return;

    try {
      await chrome.sidePanel.open({ tabId });
    } catch (error) {
      console.error('Failed to open side panel:', error);
    }
  }

  /**
   * 设置通知系统
   */
  private setupNotifications() {
    // 检查 notifications API 是否可用
    if (!chrome.notifications) {
      console.warn('Notifications API is not available');
      return;
    }

    // 监听通知点击事件
    chrome.notifications.onClicked.addListener((notificationId) => {
      console.log('Notification clicked:', notificationId);
      
      // 根据通知 ID 执行相应操作
      if (notificationId.includes('welcome')) {
        chrome.tabs.create({
          url: chrome.runtime.getURL('settings.html')
        });
      }
    });

    // 监听通知按钮点击事件
    chrome.notifications.onButtonClicked.addListener((notificationId, buttonIndex) => {
      console.log('Notification button clicked:', notificationId, buttonIndex);
    });
  }

  /**
   * 处理全局错误报告
   */
  private async handleGlobalErrorReport(errorData: any) {
    try {
      console.group(`🔴 Global Error Report - ${errorData.id}`);
      console.error('Error Type:', errorData.type);
      console.error('Error Message:', errorData.message);
      if (errorData.stack) {
        console.error('Error Stack:', errorData.stack);
      }
      if (errorData.filename) {
        console.error('File:', `${errorData.filename}:${errorData.lineno}:${errorData.colno}`);
      }
      if (errorData.element && errorData.src) {
        console.error('Resource:', `${errorData.element} - ${errorData.src}`);
      }
      console.error('URL:', errorData.url);
      console.error('Timestamp:', new Date(errorData.timestamp).toLocaleString());
      console.groupEnd();

      // 将全局错误信息存储到 chrome.storage
      const result = await chrome.storage.local.get(['globalErrorReports']);
      const existingReports = result.globalErrorReports || [];
      
      // 保留最近15个全局错误报告
      const updatedReports = [errorData, ...existingReports].slice(0, 15);
      
      await chrome.storage.local.set({ globalErrorReports: updatedReports });

      // 如果是严重错误且启用了通知，可以显示通知
      if (this.settings.enableNotifications && 
          chrome.notifications && 
          (errorData.type === 'GlobalError' || errorData.type === 'UnhandledPromiseRejection')) {
        chrome.notifications.create({
          type: 'basic',
          iconUrl: 'icons/icon48.png',
          title: '全局错误检测',
          message: `类型: ${errorData.type}\n错误: ${errorData.message.substring(0, 50)}...`
        });
      }
    } catch (error) {
      console.error('Failed to handle global error report:', error);
    }
  }
  private async handleErrorReport(errorData: any) {
    try {
      console.group(`🚨 Error Report Received - ${errorData.id}`);
      console.error('Error Message:', errorData.message);
      console.error('Error Stack:', errorData.stack);
      console.error('Component Stack:', errorData.componentStack);
      console.error('URL:', errorData.url);
      console.error('Timestamp:', new Date(errorData.timestamp).toLocaleString());
      console.groupEnd();

      // 将错误信息存储到 chrome.storage
      const result = await chrome.storage.local.get(['errorReports']);
      const existingReports = result.errorReports || [];
      
      // 保留最近20个错误报告
      const updatedReports = [errorData, ...existingReports].slice(0, 20);
      
      await chrome.storage.local.set({ errorReports: updatedReports });

      // 如果启用了通知，可以显示错误通知
      if (this.settings.enableNotifications && chrome.notifications) {
        chrome.notifications.create({
          type: 'basic',
          iconUrl: 'icons/icon48.png',
          title: '扩展遇到错误',
          message: `错误 ID: ${errorData.id.split('_')[1]}\n请检查控制台获取详细信息`
        });
      }
    } catch (error) {
      console.error('Failed to handle error report:', error);
    }
  }
}

// 初始化背景脚本
const background = new ExtensionBackground();

// 导出实例（如果需要在其他地方使用）
export default background;